package org.redhat.auth.security.core;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor;
import org.springframework.security.access.method.MethodSecurityMetadataSource;

public class AuthMethodSecurityInterceptor extends MethodSecurityInterceptor {
	// ~ Instance fields
	// ================================================================================================

	private MethodSecurityMetadataSource securityMetadataSource;

	// ~ Methods
	// ========================================================================================================

	public MethodSecurityMetadataSource getSecurityMetadataSource() {
		return this.securityMetadataSource;
	}

	public Class<? extends Object> getSecureObjectClass() {
		return MethodInvocation.class;
	}

	/**
	 * This method should be used to enforce security on a
	 * <code>MethodInvocation</code>.
	 * 
	 * @param mi
	 *            The method being invoked which requires a security decision
	 * 
	 * @return The returned value from the method invocation
	 * 
	 * @throws Throwable
	 *             if any error occurs
	 */
	public Object invoke(MethodInvocation mi) throws Throwable {
		Object result = null;
		InterceptorStatusToken token = super.beforeInvocation(mi);

		try {
			result = mi.proceed();
		} finally {
			result = super.afterInvocation(token, result);
		}

		return result;
	}

	public SecurityMetadataSource obtainSecurityMetadataSource() {
		return this.securityMetadataSource;
	}

	public void setSecurityMetadataSource(MethodSecurityMetadataSource newSource) {
		this.securityMetadataSource = newSource;
	}
}
